package cn.sdxx.qddata.controller;



import cn.sdxx.qddata.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Api(tags = "上传与下载模块")
@RestController
public class FileUploadController {

    @Value("${custom-setting.file-path.root}")
    private String rootPath;

    @Value("${custom-setting.file-path.img-upload}")
    private String imgUploadPath;

    @ApiOperation("图片上传")
    @PostMapping("/upload")
    public R upload(MultipartFile file) throws Exception {
        //创建上传目录
        String imageSavePath = rootPath + imgUploadPath;
        File imageSavePathFile = new File(imageSavePath);
        if (!imageSavePathFile.exists()) {
            imageSavePathFile.mkdirs();
        }

        //把文件的内容存储到本地磁盘上
        String originalFilename = file.getOriginalFilename();
        //保证文件的名字是唯一的,从而防止文件覆盖
        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        file.transferTo(new File(imageSavePath + filename));
        // 阿里云SSO
        // String url = AliOssUtil.uploadFile(filename,file.getInputStream());
        return R.success("图片上传成功", filename);
    }

    /**
     * 文件下载
     *
     * @param name
     * @param response
     */
    @ApiOperation("图片下载")
    @GetMapping("/upload/{name}")
    public void download(@PathVariable("name") String name, HttpServletResponse response) {
        String imageSavePath = rootPath + imgUploadPath;

        try {
            //输入流，通过输入流读取文件内容
//            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            FileInputStream fileInputStream = new FileInputStream(new File(imageSavePath  + name));

            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[8192];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
